package com.diyphonegadgets.robot.wifi;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.diyphonegadgets.robot.R;

import android.util.Log;

public class TCPCameraStreamingServer implements Runnable{
	
	boolean exception=false;
	static ServerSocket serverSocket;
	Socket client=null;
	static DataOutputStream os;
	public static boolean connected = false;

	
	   	
	 
	@Override
	public void run() {
		
		 init();
	}
	
	private void init(){
		
		try
		{
			exception=false;

			Log.i("","Creating up stream server...");
			serverSocket=new ServerSocket(8123);
			Log.i("","Up stream server created.");
		}
		catch(Exception ex)
		{
			Log.e("","Exception in creating up stream server...\n" + ex.toString());
			exception=true;
			 init();

		}
		
		Log.i("","Waiting for connection...");

		try {
			client=serverSocket.accept();
		} catch (IOException e) {

			exception=true;
			
			e.printStackTrace();
			 init();

		}

		
		/*try {
			DataInputStream is = new DataInputStream(
			        new BufferedInputStream(client.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
try {
	os = new DataOutputStream(
	            new BufferedOutputStream(client.getOutputStream(), 1024));
} catch (IOException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
	 init();

}



		if(exception==false){
		
		

			Log.i("","Done.");
			
	        connected=true;
	        
		}
		
	}
	
	
	public  static void writeImageDataToTarget(byte[] out_data){
		try {
			os.write(out_data,0,out_data.length);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		}
	
	
	public static void disconnect(){
		try {
			os.flush();
			os.close();
			serverSocket.close();
			connected=false;
		} catch (Exception e) {}
    }
		
}

